
var wImageCache = function () {
	var basePath = null;
	var pendingURL = '';
	
	//this is pretty basic, strip all non alpha numeric chars from the string
	// and append extension
	var cleanURLString = function(url){
		//urlExtension = url.substring(url.length - 3);
		url = url.replace('http://www.timesmoney.us/air/', '');
		urlExtension = url.substring(url.length - 3, url.length);
		url = url.substring(url, url.length - 3);
		url = url.replace(/[^a-zA-Z 0-9]+/g,'');
		url = url + '.' + urlExtension
		alert(url) ;
	};
	
	var setBasePath = function(){
		if(!basePath){
			basePath = new air.File("F:\\AIR\\");
		}
	};
	
	return {
		deleteFromCache: function(url){
			setBasePath();
			var cacheFile = new air.File(basePath.url + '\\' + cleanURLString(url));
			cacheFile.deleteFile();
			cacheFile = null;
		},
		get: function(url){
			setBasePath();
			
			var cacheFile = new air.File(basePath.url + '\\' + cleanURLString(url));
			if(cacheFile.exists){
				url = cacheFile.url;
			} else {
				wImageCache.add(url);
			}
			cacheFile = null;
			return url;
		},
		
		event_IOError: function (e) {
			log('Event Error, ' + e.text);
		},
		
		event_Complete: function(event){
			var loader = event.target;
			var url = pendingURL;
			var cacheFile = new air.File(basePath.url + '\\' + cleanURLString(url));
			var stream = new air.FileStream();
			
			stream.open(cacheFile,air.FileMode.WRITE);
			stream.writeBytes(loader.data);
			stream.close();
			loader = null;
			cacheFile = null;
			stream = null;
			basePath = null;
			pendingURL = '';
		},
		add: function(remoteImageURL){
			if(!pendingURL){
				var request = new air.URLRequest(remoteImageURL);
				var loader = new air.URLLoader();
        var headers = new Array();
        headers.push(new air.URLRequestHeader("Referer", "http://file.blogbus.com"));
        request.requestHeaders = headers;        
				loader.addEventListener(air.Event.COMPLETE, wImageCache.event_Complete);
				loader.addEventListener(air.IOErrorEvent.IO_ERROR, wImageCache.event_IOError);
				loader.dataFormat = air.URLLoaderDataFormat.BINARY;
				loader.load(request);
				pendingURL = cleanURLString(remoteImageURL);
			} else {
				air.trace('Already in a request //TODO add pending array');
			}
			loader = null;
			request = null;
		}
		
	};
}();